﻿package common.transaction;

import common.dao.connection.ConnectionProviderFactory;
import common.dao.connection.IConnectionProvider;
import common.proxy.ConnectionProxy;

public class TransactionControllerFactory {
	public final static String TransactionType_Connection = "Connection";
	public final static String TransactionType_Session = "Session";
	
	private static Object obj = new Object();
	private static TransactionControllerFactory instance;
	
	private ThreadLocal threadLocal = new ThreadLocal();
	
	private TransactionControllerFactory(){
		
	}
	public static TransactionControllerFactory getInstance(){
		if(instance==null){
			synchronized (obj) {
				if(instance==null){
					instance = new TransactionControllerFactory();
				}
			}
		}
		return instance;
	}
	
	/**
	 * 
	 * @param service
	 * @param transType
	 * @return
	 * @throws Exception 
	 */
	public ITransactionController createTransactionController(IServiceTransaction service, String transType) throws Exception{
		if(service instanceof IServiceTransaction){
			ITransactionController transController =  null;
			if(TransactionType_Session.equals(transType)) {
				//SessionProxy sessionProxy = getSessionProxy();
				//transController = new HibernateTransactionController(sessionProxy);
				//service.setProxyObj(sessionProxy.getProxyObj());
			} else if(TransactionType_Connection.equals(transType)) {
				//ConnectionProxy connectionProxy = getConnectionProxy();
				ConnectionProxy connectionProxy = (ConnectionProxy) threadLocal.get();
				if(connectionProxy == null){
					IConnectionProvider connectionProvider = ConnectionProviderFactory.getConnectionProvider();
					connectionProxy = new ConnectionProxy(connectionProvider.getConnection());
					threadLocal.set(connectionProxy);
				} else {
					service.setNestTransaction(true);
				}
				transController = new JdbcTransactionController(connectionProxy);
				service.setProxyObj(connectionProxy.getProxyObj());
			}
			transController.setNestTransaction(service.getNestTransaction()); 
			return transController;
		} 
		return null;
	}
	
	private ConnectionProxy getConnectionProxy() throws Exception {
		ConnectionProxy connectionProxy = (ConnectionProxy) threadLocal.get();
		if(connectionProxy == null){
			IConnectionProvider connectionProvider = ConnectionProviderFactory.getConnectionProvider();
			connectionProxy = new ConnectionProxy(connectionProvider.getConnection());
			threadLocal.set(connectionProxy);
		}
		return connectionProxy;
	}
	
	public void release(){
		Object objProxy = threadLocal.get();
		if(objProxy != null){
			objProxy = null;
			threadLocal.set(null);
		}
	}
	
	public static void clear(){
		instance.release();
	}
	
	
}
